﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TimerMgr : BaseManager<TimerMgr>
{
    public event Action<float> TimerLoopCallback;
    public Timer CreateTimer(float deltaTime,int repeatTimes,Action callback)
    {
        var timer = new Timer();
        timer.DeltaTime = deltaTime;
        timer.RepeatTimes = repeatTimes;
        timer.Callback = callback;
        return timer;
    }
    public Timer CreateTimerAndStart(float delayTime,int repeat,Action callback)
    {
        var timer = CreateTimer(delayTime,repeat,callback);
        timer.Start();
        return timer;
    }

    public void Loop(float deltaTime)
    {
        if (TimerLoopCallback != null) { TimerLoopCallback(deltaTime); }
    }

   
}
public class Timer:MonoBehaviour
{
    public float DeltaTime;
    public int RepeatTimes;
    public Action Callback;

    private float _duringTime;//计时的持续时间
    private int _repeatedTimes;//已执行了多少次,_repeatedTimes为负值时表示无限次

    public bool IsRunning = false;

    private void Reset()
    {
        _duringTime = 0;
        _repeatedTimes = 0;
        Pause();
    }
    public void Start()
    {
        Reset();
        IsRunning = true;
        TimerMgr.GetInstance().TimerLoopCallback += Loop;
        
    }
    public void Pause()
    {
        IsRunning = false;
        TimerMgr.GetInstance().TimerLoopCallback -= Loop;
        
    }
    public void Stop()
    {
        Pause();
        Reset();
    }
    public void Loop(float deltaTime)
    {
  
        _duringTime += deltaTime;
        //判断了间隔时间
      
        if (_duringTime > DeltaTime || Util.FloatEqual(DeltaTime, _duringTime))
        {
            ++_repeatedTimes;
            //Debug.Log("重复次数"+_repeatedTimes);
            _duringTime -= DeltaTime;
            if (Callback != null) { Callback(); }
            if (_repeatedTimes >= RepeatTimes&&RepeatTimes>0)
            {
                Stop();
            }
        }
    }
    private void Update()
    {
        Loop(Time.deltaTime);
    }
}
